import { Button, Col, Form, Input, Popconfirm, Row, Space, Table, Upload, message, Modal } from 'antd';
import { useCallback, useState } from 'react';
import { CloudDownloadOutlined, ImportOutlined, PlusOutlined, ReloadOutlined, SearchOutlined } from '@ant-design/icons';
import { useNavigate } from 'react-router-dom';
import basicUrl from 'src/service/basic/basic.url';
import basicService from '../../../service/basic/basic.service';
import { useRequest } from '../../../lib/request';
import './css/dealerList.scss';

const initialSearchParams = {
  coreCustName: '',
  dataOrgId: '',
  delFlag: '',
};

function DealerList(props) {
  const navigate = useNavigate();
  const [pageNum, setPageNum] = useState(1);
  const [pageSize, setPageSize] = useState(10);
  const [searchForm, setSearchForm] = useState(initialSearchParams);
  const [form] = Form.useForm();
  const params = {
    pageNum,
    pageSize,
    ...searchForm,
  };
  const [{ data = {} }, loading, query] = useRequest(
    () => basicService.getDealerList(params),
    [pageNum, pageSize, searchForm],
  );

  const formChange = useCallback((value) => {
    /**
     * 表单数值变化
     * */
    const delFlag = { 0: false, 1: true }[value.delFlag] ?? '';
    setSearchForm({
      ...value,
      delFlag,
    });
  }, []);

  const reset = useCallback(() => {
    /**
     * 重置
     * */
    form.resetFields();
    setSearchForm(form.getFieldsValue());
  }, [form]);

  function addRecord() {
    /**
     * 增加核心企业
     * */
    // 跳转新增核心企业
    navigate('/internetCommercialBank/dealer/dealerDetail');
  }

  function toDetail(record) {
    /**
     * 跳转详情
     * */
    navigate('/internetCommercialBank/dealer/dealerDetail', {
      state: {
        type: 'detail',
        detail: record,
      },
    });
  }

  function toEdit(record) {
    /**
     * 跳转编辑
     * */
    navigate('/internetCommercialBank/dealer/dealerDetail', {
      state: {
        type: 'edit',
        detail: record,
      },
    });
  }

  async function delRow(id) {
    /**
     * 删除
     * */
    const { success } = await basicService.deleteDealer(id);
    if (success) {
      query();
    }
  }

  function download() {
    /**
     * 下载模板
     * */
    basicService.downloadDealerTemplate();
  }

  const columns = [
    {
      title: '序号',
      dataIndex: 'name',
      width: 60,
      render: (...record) => {
        return <span>{record[2] + 1}</span>;
      },
    },
    {
      title: '客户编码',
      dataIndex: 'coreCustAgentNo',
      width: 120,
    },
    {
      title: '经销商名称',
      width: 200,
      dataIndex: 'agentCustName',
      textWrap: 'word-break',
      ellipsis: true,
    },
    {
      title: '统一社会信用代码',
      width: 180,
      dataIndex: 'agentCustCode',
    },
    {
      title: '法人姓名',
      width: 100,
      dataIndex: 'agentCustFrName',
    },
    {
      title: '法人身份证号',
      width: 150,
      dataIndex: 'agentCustFrCode',
    },
    {
      title: '合作月份',
      width: 120,
      dataIndex: 'custCoopMonth',
    },
    {
      title: '行业类型',
      width: 120,
      dataIndex: 'dataindustryName',
    },
    {
      title: '核心企业名称',
      width: 150,
      dataIndex: 'coreCustName',
    },
    {
      title: '核心企业统一社会信用代码',
      width: 200,
      dataIndex: 'coreCustCode',
    },
    {
      title: '是否变更',
      width: 100,
      dataIndex: '',
      render: () => '否',
    },
    {
      title: '操作',
      width: 140,
      fixed: 'right',
      render: (text, record) => (
        <Space size={10}>
          <span
            className="common-link"
            onClick={() => {
              toEdit(record);
            }}
          >
            编辑
          </span>
          <Popconfirm title="确定要删除吗?" onConfirm={() => delRow(record.id)}>
            <span className="common-link">删除</span>
          </Popconfirm>
          <span
            className="common-link"
            onClick={() => {
              toDetail(record);
            }}
          >
            详情
          </span>
        </Space>
      ),
    },
  ];

  const uploadProps = {
    name: 'file',
    accept: '.xlsx,.xls',
    action: process.env.REACT_APP_BASE_URL + basicUrl.uploadDealer,
    headers: {
      JINJUTOKEN: localStorage.getItem('token'),
    },
    onChange(info) {
      const file = info.file;
      // if (file.status !== 'uploading') {
      //   console.log(file, fileList);
      // }
      if (file.status === 'done') {
        const res = file.response;
        if (res.success) {
          const msg = [res.msg];
          const msgData = res.data;
          if (msgData && msgData.length) {
            msg.push(...msgData);
            Modal.info({
              title: '提示',
              content: (
                <div className="text-left">
                  {msg.map((v) => (
                    <div>{v}</div>
                  ))}
                </div>
              ),
            });
            return;
          }
          message.success(`${file.name}导入成功`);
          query();
        } else {
          Modal.error({
            title: '提示',
            content: res.msg,
          });
        }
      } else if (file.status === 'error') {
        Modal.error({
          title: '提示',
          content: `${file.name}导入失败`,
        });
      }
    },
  };

  return (
    <div>
      <Form
        form={form}
        name=""
        initialValues={initialSearchParams}
        className="common-table-search-wrap"
        onFinish={formChange}
      >
        <Row gutter={24}>
          <Col span={6}>
            <Form.Item name="agentCustName" label="经销商名称">
              <Input placeholder="请输入经销商名称" allowClear />
            </Form.Item>
          </Col>
          <Col span={6}>
            <Form.Item name="coreCustName" label="核心企业名称">
              <Input placeholder="请输入核心企业名称" allowClear />
            </Form.Item>
          </Col>
          <Col span={6}>
            <Form.Item name="agentCustFrName" label="法人姓名">
              <Input placeholder="请输入法人姓名" allowClear />
            </Form.Item>
          </Col>
          {/* <Col span={6}> */}
          {/*  <Form.Item */}
          {/*    name="delFlag" */}
          {/*    label="状态" */}
          {/*  > */}
          {/*    <Select> */}
          {/*      <Option value="" disabled>请选择</Option> */}
          {/*      <Option value="1">正常</Option> */}
          {/*      <Option value="0">停用</Option> */}
          {/*    </Select> */}
          {/*  </Form.Item> */}
          {/* </Col> */}
        </Row>
        <Row justify="end" className="common-table-search-btn-wrap">
          <Col span={6}>
            <Button type="primary" htmlType="submit" icon={<SearchOutlined />}>
              搜索
            </Button>
            <Button icon={<ReloadOutlined />} onClick={reset}>
              重置
            </Button>
          </Col>
        </Row>
      </Form>
      <Row className="common-table-operation-wrap">
        <Col>
          <Space size={30}>
            <Button type="primary" icon={<PlusOutlined />} onClick={addRecord}>
              新增
            </Button>
            <Upload {...uploadProps} className="dealerList-upload-wrap">
              <Button type="primary" icon={<ImportOutlined />}>
                批量导入
              </Button>
            </Upload>
            <Button type="primary" icon={<CloudDownloadOutlined />} onClick={download}>
              模板下载
            </Button>
          </Space>
        </Col>
      </Row>
      <Table
        rowKey="id"
        columns={columns}
        loading={loading}
        dataSource={data?.list || []}
        scroll={{
          x: 'max-content',
        }}
        pagination={{
          position: ['bottomRight'],
          showSizeChanger: true,
          current: pageNum,
          total: data?.total || 0,
          showTotal: (total) => `共 ${total} 条数据`,
          onChange: (num, size) => {
            let tempNum = num;
            if (size !== pageSize) {
              setPageSize(size);
              tempNum = 1;
            }
            setPageNum(tempNum);
          },
        }}
      />
    </div>
  );
}

export default DealerList;
